package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.Constant;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.controller.app.PushController;
import com.hboxs.asl.entity.Letter;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.service.LetterService;
import com.hboxs.asl.service.MemberService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Controller(value = "appLetterController")
@RequestMapping(value = "/app/m/letter")
public class LetterController extends BaseController {

    @Resource(name = "letterServiceImpl")
    private LetterService letterService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;

    /**
     * 发送私信
     * @param receiverId
     * @param content
     * @return
     */
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage send(Long receiverId, String content) {
        try {
            Member sender = memberService.getCurrentByToken();
            if (sender == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Member receiver = memberService.find(receiverId);
            if (receiver == null) {
                return JsonMessage.error("找不到该用户");
            }
            if (sender.getId().equals(receiverId)) {
                return JsonMessage.error("不能给自己发私信");
            }
            //判断是否发送过信息
            Letter letter = letterService.ifHasSend(sender, receiver);
            if (letter == null) {
                //判断是否发送过信息
                Letter letter1 = letterService.ifHasSend(receiver, sender);
                if (letter1 != null) {
                    letterService.replyLetter(sender, receiver, content, letter1.getId());
                    PushController.notice(receiver, sender.getName()+Constant.LETTER_CONTENT);
                } else {
                    //保存私信
                    letterService.generateLetter(sender, receiver, content);
                    PushController.notice(receiver, sender.getName()+Constant.LETTER_CONTENT);
                }
            } else {
                //回复私信
                letterService.replyLetter(sender, receiver, content, letter.getId());
                PushController.notice(receiver, sender.getName()+Constant.LETTER_CONTENT);
            }
            return JsonMessage.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 回复私信
     * @param receiverId
     * @param content
     * @param letterId
     * @return
     */
    @RequestMapping(value = "/reply", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage reply(Long receiverId, String content, Long letterId) {
        try {
            Member sender = memberService.getCurrentByToken();
            if (sender == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Member receiver = memberService.find(receiverId);
            if (receiver == null) {
                return JsonMessage.error("找不到该用户");
            }
            //回复私信
            letterService.replyLetter(sender, receiver, content, letterId);
            return JsonMessage.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 获取我的私信列表
     * @return
     */
    @RequestMapping(value = "/letters", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage letters(Pageable pageable) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            //获取所有接收者为当前有用户的原信息
            List<Letter> letterList = letterService.findLetterPage(member);
            Page<Letter> page = letterService.findPageLetter(pageable, letterList);
            return JsonMessage.success(

                    "totalPage", page.getTotalPages(),

                    "pageNumber", page.getPageNumber(),

                    "pageSize", page.getPageSize(),

                    "total", page.getTotal(),

                    "content", JsonMessage.optimiseObj(page.getContent(), "id", "content", "sender.id", "sender.name", "sender.avator", "sender.username","sender.type",
                            "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiver.type", "receiverRead", "createDateF")
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

//    /**
//     * 私信详情
//     * @param letterId
//     * @return
//     */
//    @RequestMapping(value = "/detail", method = RequestMethod.GET)
//    public
//    @ResponseBody
//    JsonMessage letterDetail(Long letterId, Pageable pageable) {
//        try {
//            Letter letter = letterService.find(letterId);
//            if (letter == null) {
//                return JsonMessage.error("找不到对应的私信");
//            }
//            List<Letter> letterList = letterService.findLetterDetailList(letter);
//            letterList.add(letter);
//            Page<Letter> page = letterService.findPageLetter(pageable, letterList);
//            return JsonMessage.success(
//
//                    "totalPage", page.getTotalPages(),
//
//                    "pageNumber", page.getPageNumber(),
//
//                    "pageSize", page.getPageSize(),
//
//                    "total", page.getTotal(),
//
//                    "content", JsonMessage.optimiseObj(page.getContent(), "content", "sender.id", "sender.name", "sender.avator", "sender.username",
//                            "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiverRead", "createDateF")
//            );
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//        }
//        return JsonMessage.UNKNOWN_ERROR;
//    }

    /**
     * 用户与用户之间私信详情
     * @return
     */
    @RequestMapping(value = "/letter_detail", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage detail(Long teacherId, Pageable pageable) {
        try {
            Member sender = memberService.getCurrentByToken();
            if (sender == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Member receiver = memberService.find(teacherId);
            if (receiver == null) {
                return JsonMessage.error("找不到该用户");
            }
            //判断是否发送过信息
            Letter letter = letterService.ifHasSend(sender, receiver);
            if (letter == null) {
                Letter letter1 = letterService.ifHasSend(receiver, sender);
                if ( letter1 != null) {
                    List<Letter> letterList = letterService.findLetterDetailList(letter1);
                    letterList.add(letter1);
                    Page<Letter> page = letterService.findPageLetter(pageable, letterList);
                    //顺序颠倒
                    Collections.reverse(page.getContent());
                    return JsonMessage.success(

                            "totalPage", page.getTotalPages(),

                            "pageNumber", page.getPageNumber(),

                            "pageSize", page.getPageSize(),

                            "total", page.getTotal(),

                            "content", JsonMessage.optimiseObj(page.getContent(), "content", "sender.id", "sender.name", "sender.avator", "sender.username",
                                    "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiverRead", "createDateF")
                    );
                } else {
                    Page<Letter> page = new Page<>();
                    return JsonMessage.success(

                            "totalPage", page.getTotalPages(),

                            "pageNumber", page.getPageNumber(),

                            "pageSize", page.getPageSize(),

                            "total", page.getTotal(),

                            "content", JsonMessage.optimiseObj(page.getContent(), "content", "sender.id", "sender.name", "sender.avator", "sender.username",
                                    "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiverRead", "createDateF")
                    );
                }

            } else {
                List<Letter> letterList = letterService.findLetterDetailList(letter);
                letterList.add(letter);
                Page<Letter> page = letterService.findPageLetter(pageable, letterList);
                //顺序颠倒
                Collections.reverse(page.getContent());
                return JsonMessage.success(

                        "totalPage", page.getTotalPages(),

                        "pageNumber", page.getPageNumber(),

                        "pageSize", page.getPageSize(),

                        "total", page.getTotal(),

                        "content", JsonMessage.optimiseObj(page.getContent(), "content", "sender.id", "sender.name", "sender.avator", "sender.username",
                                "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiverRead", "createDateF")
                );
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

//    /**
//     * 用户与用户之间私信详情
//     * @return
//     */
//    @RequestMapping(value = "/detail", method = RequestMethod.GET)
//    public
//    @ResponseBody
//    JsonMessage Ldetail(Long teacherId, Pageable pageable) {
//        try {
//            Member sender = memberService.getCurrentByToken();
//            if (sender == null) {
//                return JsonMessage.USER_NOT_LOGIN;
//            }
//            Member receiver = memberService.find(teacherId);
//            if (receiver == null) {
//                return JsonMessage.error("找不到该用户");
//            }
//            //判断是否发送过信息
//            Letter letter = letterService.ifHasSend(sender, receiver);
//            if (letter == null) {
//                Letter letter1 = letterService.ifHasSend(receiver, sender);
//                if ( letter1 != null) {
//                    Set<Letter> letterSet = letter1.getReplyLetteres();
//                    List<Letter> letterList = new ArrayList<>(letterSet);
//                    letterList.add(letter1);
//                    Page<Letter> page = letterService.findPageLetter(pageable, letterList);
//                    //顺序颠倒
//                    Collections.reverse(page.getContent());
//                    return JsonMessage.success(
//
//                            "totalPage", page.getTotalPages(),
//
//                            "pageNumber", page.getPageNumber(),
//
//                            "pageSize", page.getPageSize(),
//
//                            "total", page.getTotal(),
//
//                            "content", JsonMessage.optimiseObj(page.getContent(), "content", "sender.id", "sender.name", "sender.avator", "sender.username",
//                                    "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiverRead", "createDateF")
//                    );
//                } else {
//                    Page<Letter> page = new Page<>();
//                    return JsonMessage.success(
//
//                            "totalPage", page.getTotalPages(),
//
//                            "pageNumber", page.getPageNumber(),
//
//                            "pageSize", page.getPageSize(),
//
//                            "total", page.getTotal(),
//
//                            "content", JsonMessage.optimiseObj(page.getContent(), "content", "sender.id", "sender.name", "sender.avator", "sender.username",
//                                    "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiverRead", "createDateF")
//                    );
//                }
//
//            } else {
//                Set<Letter> letterSet = letter.getReplyLetteres();
//                List<Letter> letterList = new ArrayList<>(letterSet);
//                letterList.add(letter);
//                Page<Letter> page = letterService.findPageLetter(pageable, letterList);
//                //顺序颠倒
//                Collections.reverse(page.getContent());
//                return JsonMessage.success(
//
//                        "totalPage", page.getTotalPages(),
//
//                        "pageNumber", page.getPageNumber(),
//
//                        "pageSize", page.getPageSize(),
//
//                        "total", page.getTotal(),
//
//                        "content", JsonMessage.optimiseObj(page.getContent(), "content", "sender.id", "sender.name", "sender.avator", "sender.username",
//                                "receiver.id", "receiver.name", "receiver.avator", "receiver.username", "receiverRead", "createDateF")
//                );
//            }
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//        }
//        return JsonMessage.UNKNOWN_ERROR;
//    }

    /**
     * 设置为接收者已读
     * @param letterId
     * @return
     */
    @RequestMapping(value = "hasRead", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage hasRead(Long letterId) {
        try {
            //获取接收者
            Member receiver = memberService.getCurrentByToken();
            if (receiver == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            //设置接收者已读信息
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }
}
